package jude.java.money.sly;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jude.java.util.WebUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class FindSites {
	static final Log L = LogFactory.getLog(FindSites.class);
	
	private static final String REGEXP = "<a href=\"http://([^\"]+)\" target=_blank class=l onmousedown=\"return (rwt|clk)\\(";
	private String googleUrl;
	private HttpClient client;
	
	public FindSites(String googleUrl) {
		this.googleUrl = googleUrl;
		
	}
	
	public List<String> find() {
		
		this.client = new DefaultHttpClient();
		String resp = getContent(googleUrl);
//		resp = "<h3 class=\"r\"><a href=\"http://www.uggoutlet-store.org/\" target=_blank class=l onmousedown=\"return clk(0,'','','','4','','0CB8QFjAD')\">";
		if (StringUtils.isEmpty(resp))
			return null;
		
		return find(resp);
	}
	
	/*
<h3 class="r"><a href="http://www.uggoutlet-store.org/" target=_blank class=l onmousedown="return clk(0,'','','','4','','0CB8QFjAD')">
	 * */
	private List<String> find(String content) {
		List<String> r = new ArrayList<String>();
		Pattern p = Pattern.compile(REGEXP);
		Matcher m = p.matcher(content);
		int n = 0;
		while (m.find(n)) {
			String domain = m.group(1);
			int c = domain.indexOf('/');
			if (c != -1) {
				domain = domain.substring(0, c);
			}
			r.add(domain);
			n = m.end();
		}
		return r;
	}
	
	private String getContent(String url) {
		HttpGet get = new HttpGet(url);
//		GetMethod get = new GetMethod(url);
		WebUtils.pretendRequestHeader(get);
		get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
//		get.setFollowRedirects(true);
		try {
			HttpResponse response = client.execute(get);
			int statusCode = response.getStatusLine().getStatusCode();
//			int statusCode = client.executeMethod(get);
			if (statusCode != HttpStatus.SC_OK) {
				get.abort();
				return null;
			}
			String resp = WebUtils.getResponse(response, 0, "UTF-8");
			return resp;
		} catch (SocketException e) {
			if ("Software caused connection abort: recv failed".equals(e.getMessage())) {
				throw new RuntimeException("blocked by google");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
